@echo off
chcp 65001 >nul
echo ========================================
echo    Handheld 4G Signal Detection System
echo ========================================
echo.

:: Set ADB path
set ADB_PATH=D:\Android\android-sdk\platform-tools\adb.exe

:: Check ADB availability
echo [1/6] Checking ADB connection...
"%ADB_PATH%" devices >nul 2>&1
if %errorlevel% neq 0 (
    echo ERROR: ADB not found or not configured properly
    echo Please ensure Android SDK is installed and environment variables are set
    echo Current ADB path: %ADB_PATH%
    pause
    exit /b 1
)

:: Check device connection
echo [2/6] Checking device connection...
for /f "tokens=1" %%i in ('"%ADB_PATH%" devices ^| findstr "device$"') do set DEVICE_ID=%%i
if "%DEVICE_ID%"=="" (
    echo ERROR: No Android device found
    echo Please ensure device is connected and USB debugging is enabled
    pause
    exit /b 1
)
echo Device connected: %DEVICE_ID%

:: 清理之前的日志
echo [3/6] 清理日志缓存...
"%ADB_PATH%" logcat -c
echo ✅ 日志缓存已清理

:: 构建应用
echo [4/6] 构建应用...
echo 正在编译和安装应用...
call gradlew assembleDebug
if %errorlevel% neq 0 (
    echo ❌ 构建失败
    pause
    exit /b 1
)

call gradlew installDebug
if %errorlevel% neq 0 (
    echo ❌ 安装失败
    pause
    exit /b 1
)
echo ✅ 应用构建并安装成功

:: 启动应用
echo [5/6] 启动应用...
"%ADB_PATH%" shell am start -n com.example.handheld4_gsignal_app/.MainActivity
if %errorlevel% neq 0 (
    echo ❌ 应用启动失败
    pause
    exit /b 1
)
echo ✅ 应用启动成功

:: 开始日志监控
echo [6/6] 开始日志监控...
echo.
echo ========================================
echo           开始监控应用日志
echo ========================================
echo 按 Ctrl+C 停止监控
echo 应用包名: com.example.handheld4_gsignal_app
echo ========================================
echo.

:: 监控应用日志
"%ADB_PATH%" logcat -s "handheld4_gsignal_app" -v time

pause